package com.securecrt;

import java.io.IOException;

import com.securecrt.Utils;
import com.securecrt.sql.SQLHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Locale;

import org.xmlpull.v1.XmlSerializer;

import android.widget.TextView;


import com.jcraft.jsch.Channel;
import com.jcraft.jsch.Session;

public class ssh2 extends Activity {
	
    TextView tvprotocol,tvHostname,tvPort,tvUsername,tvPassword,tvlinksession;
    Session session;
    Channel channel;
    SSHClient conn;
    
	EditText host;
	EditText port;
	EditText user;
	EditText pass;
	Button btnConn;
	Button btBack, btHome,btvn,bten,btkr;
	private Handler mHandler = new Handler();
	
	Spinner protocol;
	Spinner cipher;
	Spinner mac;
	CheckBox save_session;
	private boolean checked=false;
	SQLHelper eventsData;
	ProgressDialog pro;
	private String str1="",str2="";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.ssh2);
        //update = new AutoUpdateApk(getApplicationContext());       //and add this line too
        
        protocol = (Spinner)findViewById(R.id.protocol);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.protocol ,android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        protocol.setAdapter(adapter);
        protocol.setSelection(3);
        protocol.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String name = parent.getItemAtPosition(position).toString();
				if(name.equals("ssh2")){
					return;
				}
				String classSelected = "com.securecrt." + name.toUpperCase();
				Intent intent = new Intent(classSelected);
				startActivity(intent);
				finish();
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
        
        cipher = (Spinner)findViewById(R.id.cipher);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.cipher ,android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cipher.setAdapter(adapter2);
        cipher.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
        
        mac = (Spinner)findViewById(R.id.mac);
        ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this, R.array.mac ,android.R.layout.simple_spinner_item);
        adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mac.setAdapter(adapter3);
        mac.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
        });
        
        host=(EditText)findViewById(R.id.etHostname);
        user=(EditText)findViewById(R.id.etUsername);
        pass=(EditText)findViewById(R.id.etPassword);
        port=(EditText)findViewById(R.id.etPort);
        
        btnConn=(Button)findViewById(R.id.btnConnect);
        btnConn.setOnClickListener(onClickListenerConn);
        btBack = (Button) findViewById(R.id.btBack);
		btHome = (Button) findViewById(R.id.btHome);
		btBack.setOnClickListener(onBackClick());
		btHome.setOnClickListener(onHomeClick());
                
		tvprotocol=(TextView)findViewById(R.id.tvprotocol);
		tvHostname=(TextView)findViewById(R.id.tvHostname);
		tvPort=(TextView)findViewById(R.id.tvPort);
		tvUsername=(TextView)findViewById(R.id.tvUsername);
		tvPassword=(TextView)findViewById(R.id.tvPassword);
		
        btvn=(Button)findViewById(R.id.btvn);btvn.setOnClickListener(onClickbtvn());
        bten=(Button)findViewById(R.id.bten);bten.setOnClickListener(onClickbten());
        btkr=(Button)findViewById(R.id.btkr);btkr.setOnClickListener(onClickbtkr());

        save_session=(CheckBox)findViewById(R.id.save_session);
        save_session.setOnCheckedChangeListener(ChecKedChangeListener);
        eventsData=new SQLHelper(this);
        
        tvlinksession=(TextView)findViewById(R.id.tvlinksession);
        tvlinksession.setOnClickListener(OnClickLinksession);
        
    }

    private OnClickListener OnClickLinksession=new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			passSaveSession();
		}
	};

    private OnCheckedChangeListener ChecKedChangeListener=new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			// TODO Auto-generated method stub
			if(buttonView.isChecked()){
				checked=true;
			}else{
				checked=false;
			}
		}
	};
    
    private void passSaveSession(){
    	Intent i=new Intent(this, SaveSession.class);
    	i.putExtra("host",host.getText().toString());
		i.putExtra("port", port.getText().toString());
		i.putExtra("user", String.valueOf(user.getText().toString()));
		i.putExtra("pass", pass.getText().toString());
    	startActivity(i);
    }
    private void refresh() {
        finish();
        Intent myIntent = new Intent(ssh2.this, ssh2.class);
        startActivity(myIntent);
    }
    private OnClickListener onClickbtvn(){
    	OnClickListener onClickbtvn=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("vn");refresh();
			}
		};
    	return onClickbtvn;
    }
    private OnClickListener onClickbten(){
    	OnClickListener onClickbten=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("en");refresh();
			}
		};
    	return onClickbten;
    }

    private OnClickListener onClickbtkr(){
    	OnClickListener onClickbtkr=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("kr");refresh();
			}
		};
    	return onClickbtkr;
    }
    private void changuageLang(String lang){
		Locale locale=new Locale(lang);
        Locale.setDefault(locale);
        Configuration config=new Configuration();
        config.locale=locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }

    private void initForm(){
    	host.setText(this.getPreferences(0).getString("server","ftp.elisoft.co.kr"));
    	user.setText(this.getPreferences(0).getString("user","elisoft"));
    	
    }

	private void loadingShow(){
    	pro=ProgressDialog.show(this, "", getString(R.string.waiting)+"...");
    }
    
    private boolean checkSession(){
    	boolean ch=false;
    	Cursor cursor=getEvents();
        if(showEvents(cursor))
        	return ch=true;
        return ch;
    }
    private Cursor getEvents(){
		SQLiteDatabase db=eventsData.getReadableDatabase();
		Cursor cursor=db.query(SQLHelper.TABLE, null, null, null, null,null, null);
		startManagingCursor(cursor);
		return cursor;
	}

	private boolean showEvents(Cursor cursor){
		boolean ch=false;
		String ho=host.getText().toString();
		String po=port.getText().toString();
		String us=String.valueOf(user.getText().toString());
		String pa=pass.getText().toString();
		while(cursor.moveToNext()){
			long id =cursor.getLong(0);
			String hostname=cursor.getString(1);
			String port=cursor.getString(2);
			String username=cursor.getString(3);
			String password=cursor.getString(4);
			if(hostname.equals(ho)&&port.equals(po)&&username.equals(us)&&password.equals(pa))
				return ch=true;
		}
		return ch;
	}
    private OnClickListener onClickListenerConn=new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			final String hotname=host.getText().toString();
			final int p=Integer.parseInt(port.getText().toString());
			final String username=user.getText().toString();
			final String password=pass.getText().toString();
			final String cip = cipher.getSelectedItem().toString();
			final String mac1 = mac.getSelectedItem().toString();
			if(hotname.trim().equals("")){
				Utils.showErrorMessage(ssh2.this,getString(R.string.errHost));					    		
	    		return;
			}
	    	if(username.trim().equals("")){
	    		Utils.showErrorMessage(ssh2.this,getString(R.string.errUser));					    		
	    		return;
			}
	    	if(password.trim().equals("")){
	    		Utils.showErrorMessage(ssh2.this,getString(R.string.errPass));						    		
	    		return;
			}
	    	String sPort=port.getText().toString().trim();
	    	boolean isBadPort=false;
	    	int iPort=0;
	    	try{
	    		iPort=Integer.parseInt(sPort);
	    	}
	    	catch (Exception e) {
				isBadPort=true;
			}
	    	if(iPort<=0||iPort>=65535){
	    		isBadPort=true;
	    	}
	    	if(isBadPort){
	    		Utils.showErrorMessage(ssh2.this,getString(R.string.errPort));					    		
	    		return;
	    	}
	    	
			loadingShow();
	    	new Thread() {
	            public void run() {
	              
						try {
							
							if(connectSSH(hotname, p, username, password, cip, mac1)){
								//onCommand();
								String classSelected = "com.securecrt.TERMINAL";
								if(checked && !checkSession()){
									//save session
									saveSessionActive();
								}
								Intent intent = new Intent(classSelected);
								intent.putExtra("server",hotname);
								intent.putExtra("user", username);
								intent.putExtra("port", String.valueOf(p));
								intent.putExtra("pass", password);
								intent.putExtra("cipher", cip);
								intent.putExtra("mac", mac1);
								startActivity(intent);
								conn.disconnect();
							}else{
								pro.dismiss();
								//Utils.showErrorMessage(ssh2.this,"SSH Connect Fault.");
								Toast.makeText(ssh2.this,"SSH Connect Fault.", Toast.LENGTH_SHORT).show();			
								return;

							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							//pro.dismiss();							
							e.printStackTrace();
						}
						pro.dismiss();						
	              }

	    		}.start();
	    		
		}
	};

	private OnClickListener onBackClick() {
		OnClickListener onBackClick = new OnClickListener() {
			@Override
			public void onClick(View v) {
				moveTaskToBack(true);	
				finish();
				System.exit(0);
			}
		};
		return onBackClick;
	}
	
	private OnClickListener onHomeClick() {
		OnClickListener onHomeClick = new OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				finish();
				System.exit(0);

			}
		};
		return onHomeClick;
	}
	public boolean connectSSH(String host, int port, String username, String password, String cipher, String mac) throws IOException{
            try {
                conn = new SSHClient(username,password,host, port,cipher,mac);
                return true;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
                return false;
            }
    }

    private void saveSessionActive(){
    	SQLiteDatabase db=eventsData.getWritableDatabase();
		ContentValues values=new ContentValues();
		values.put(SQLHelper.HOSTNAME, host.getText().toString());
		values.put(SQLHelper.PORT, port.getText().toString());
		values.put(SQLHelper.USERNAME, String.valueOf(user.getText().toString()));
		values.put(SQLHelper.PASSWORD, pass.getText().toString());
		db.insert(SQLHelper.TABLE, null, values);
    }
    
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_ENTER:
			Toast.makeText(this, str2, Toast.LENGTH_LONG).show();
			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
}
